package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.biz.api.entity.WxDept;
import com.oceansoft.mobile.biz.api.entity.WxDeptResevre;
import com.oceansoft.mobile.biz.api.entity.WxReserve;
import com.oceansoft.mobile.biz.api.service.IApiHzyyService;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * Created by Administrator on 2016/4/27.
 */
@Controller
@RequestMapping("api/hzyy")
public class ApiHzyyController {
    @Resource
    public IApiHzyyService apiHzyyService;
    //告知办案单位
    public static String  Police_Bureaus= Constant.host5+"api/police/Police_Bureaus";
    //网上预约
    public static String police_stations =Constant.host5+"api/police/police_stations?guid=";

    private final static int num=1;
    //网上预约数据存到网厅
    public static String hzyy =Constant.host5+"api/Product/SaveReserve";

    /*
     * 获取所有分局，派出所，放到本地数据库
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "Police_Bureaus")
    public void Police_Bureaus() throws IllegalArgumentException, IOException {
        Result result =  JSONObject.parseObject(HttpClientUtil.doGet(Police_Bureaus),Result.class);
        JSONArray jsonArray =JSONObject.parseArray(result.getData().toString());
        for(int i =0;i<jsonArray.size();i++){
            apiHzyyService.saveDept(jsonArray.getJSONObject(i),"");
            Result result1 =  JSONObject.parseObject(HttpClientUtil.doGet(police_stations+jsonArray.getJSONObject(i).get("ORGID")),Result.class);
            JSONArray array =JSONObject.parseArray(result1.getData().toString());
            for(int j =0;j<array.size();j++){
                apiHzyyService.saveDept(array.getJSONObject(j),jsonArray.getJSONObject(i).get("ORGID").toString());
            }
        }
    }
    /**
     * 判断是否节假日
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "isHoliday", method = GET)
    public String isHoliday(HttpServletRequest request) throws IllegalArgumentException, IOException, ParseException {
        String date = request.getParameter("date");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
        Date d = df.parse(date);
        date=df1.format(d);
        int b = apiHzyyService.isHoliday(date);
        return String.valueOf(b);
    }
    /**
     * 返回部门数据，分局parentid ="",派出所就是orgid
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "getDept")
    public List<WxDept> getDept(HttpServletRequest request,Model model) throws IllegalArgumentException, IOException {
        String openId = (String)request.getSession().getAttribute("openId");
        String parentid = request.getParameter("parentid");
        List<WxDept> list = apiHzyyService.getDept(parentid);
        return list;
    }
    /**
     * 查询可预约数
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "getRevnum")
    public WxDeptResevre getRevnum(HttpServletRequest request,Model model) throws IllegalArgumentException, IOException {
        String orgid = request.getParameter("orgid");
        String date = request.getParameter("date");
        date = date.replaceAll("-","");
        String openId= (String) request.getSession().getAttribute("openId");
        Member member = (Member)request.getSession().getAttribute(Constant.SESSION_USER);
        System.out.print("==========="+member.getGuid());
        //先拿到部门预先设置好的每日预约总数
        WxDeptResevre wxDeptResevre = apiHzyyService.getRevnum(orgid);
        //判断当前时间，当前部门是否有过预约
        int i=apiHzyyService.checkIsRev(date,orgid);
        //如果已有过预约
        if(i>0){
            //拿到当前日期已预约数量,为方便，存放在WxDeptResevre这个对象中
            WxDeptResevre wxresevre =apiHzyyService.getsumnumBydate(date,orgid);
            //计算剩余量
            wxDeptResevre.setSbnum(wxDeptResevre.getSbnum()-wxresevre.getSbnum());
            wxDeptResevre.setZxnum(wxDeptResevre.getZxnum() - wxresevre.getZxnum());
            wxDeptResevre.setQynum(wxDeptResevre.getQynum() - wxresevre.getQynum());
            wxDeptResevre.setDjnum(wxDeptResevre.getDjnum() - wxresevre.getDjnum());
        }
        //获取当前时间用户是否已经预约
        WxDeptResevre resevre =apiHzyyService.getsumnumBydateAndOpenId(date,orgid,member.getGuid());
        wxDeptResevre.setIssb(resevre.getIssb());
        wxDeptResevre.setIsdj(resevre.getIsdj());
        wxDeptResevre.setIszx(resevre.getIszx());
        wxDeptResevre.setIsqy(resevre.getIsqy());
        return wxDeptResevre;
    }
    /**
     * 用户预约申报
     *
     * @return Result
     */
    @ResponseBody
    @RequestMapping(value = "revHk")
    public Result submitRevHk(HttpServletRequest request,WxReserve wxReserve) {
        Result re = new Result();
        String openId = (String)request.getSession().getAttribute("openId");
        Member member = (Member)request.getSession().getAttribute(Constant.SESSION_USER);
        if("0".equals(wxReserve.getType())){
            wxReserve.setSbnum(1);
        }else if("1".equals(wxReserve.getType())){
            wxReserve.setQynum(1);
        }
        else if("2".equals(wxReserve.getType())){
            wxReserve.setDjnum(1);
        }
        else if("3".equals(wxReserve.getType())){
            wxReserve.setZxnum(1);
        }
        wxReserve.setXm(member.getRealName());
        SimpleDateFormat sdf=new SimpleDateFormat("yyMMdd");
        SimpleDateFormat sdf2=new SimpleDateFormat("yy-MM-dd");
        java.util.Date date=new java.util.Date();
        String str=sdf.format(date);
        Random random= new Random();
        int randNum = random.nextInt(8999)+1000;
        wxReserve.setBjbh("YY"+str+randNum);
        wxReserve.setLxdh(member.getMobile());
        wxReserve.setOpenId(openId);
        wxReserve.setSfzh(member.getIdCard());
        wxReserve.setUserguid(member.getGuid());
        wxReserve.setCreatedate(sdf2.format(new Date()));
        //判断当前用户是否有过该日期下的该项预约
        boolean result = apiHzyyService.checkRecByopenId(wxReserve);
        if(result){
            boolean  b = apiHzyyService.insertRev(wxReserve);
            System.out.print("========="+b);
            //将数据同时存到网上办事大厅内网数据库
            Map<String, String> param = new HashMap<String, String>();
            param.put("DEPTID",wxReserve.getDeptid());
            param.put("DATETIME",wxReserve.getDate());
            param.put("SBNUM",wxReserve.getSbnum()+"");
            if(wxReserve.getZxnum()==1){
                param.put("SBNUM","2");
            }
            if(wxReserve.getQynum()==1){
                param.put("SBNUM","3");
            }
            if(wxReserve.getDjnum()==1){
                param.put("SBNUM","4");
            }
          /*  param.put("ZXNUM",wxReserve.getZxnum()+"");
            param.put("QYNUM",wxReserve.getQynum()+"");
            param.put("DJNUM",wxReserve.getDjnum()+"");*/
            param.put("OPENID",wxReserve.getOpenId());
            param.put("XM",wxReserve.getXm());
            param.put("BJBH",wxReserve.getBjbh());
            param.put("LXDH",wxReserve.getLxdh());
            param.put("SFZH",wxReserve.getSfzh());
            param.put("USERGUID",wxReserve.getUserguid());
            Result rst = JSONObject.parseObject(HttpClientUtil.doPost(hzyy, param, "utf-8"), Result.class);

            re.setSucc(b);
            if(b){
                re.setMsg("预约成功！");
            }else{
                re.setMsg("预约失败，请稍后重试！");
            }
        }else{
            re.setSucc(result);
            re.setMsg("您当前日期已有预约！");
        }



        return re;
    }
}
